<template>
  <view class="box">
    <view class="to"
          @click="toTo()"
          v-if="param.to">{{ handleTo(param) }}
      <view style="transform: rotate(-180deg);display: inline-block;margin-top: 10rpx;vertical-align: top">{{ "➠" }}
      </view>
    </view>
    <view style="height: 10rpx"></view>
    <view class="input-box">
      <view class="verify-code-input-box">
        <input
            class="code-input"
            type="number"
            @focus="focus()"
            @blur="blur()"
            v-model="param.value"
            maxlength="6"
            :adjust-position="false"
            :placeholder="isFocus?'':$i18n.zhToGlobal('验证码')">
        </input>
      </view>
      <view style="height: 50rpx"></view>
      <view>
        <view v-show="!isCheck">
          <kt-button
              v-show="isSending"
              style="opacity: .8"
              @click="sendCode()">{{ surplusTime }}
          </kt-button>
          <kt-button
              v-show="!isSending"
              ref="sendCodeButton"
              @click="sendCode()">{{$i18n.zhToGlobal('发送验证码')}}
          </kt-button>
        </view>
        <view v-show="isCheck">
          <kt-button ref="checkButton">···</kt-button>
        </view>


      </view>
    </view>

  </view>
</template>

<script>

import VerifyBox from "@/pages/login/components/VerifyBox.vue";

export default {
  components: {VerifyBox},
  data() {
    return {
      isFocus: false,
      param: {
        to: "",
        typeCode: "",
        value: "",
        loginTypeCode: "verificationCode"
      },
      isSending: false,
      // 剩余时间(秒)
      surplusTime: 0,
      // 是否校验中
      isCheck: false,

    };
  },
  created() {
    if (this.$kt.storage.get("loginParam")) {
      this.param = this.$kt.storage.get("loginParam");
    }

    // 设置剩余时间
    let sendCodeTime = this.$kt.storage.get("sendCodeTime");
    if (sendCodeTime) {
      let surplusTime = 60 - Math.floor((new Date().getTime() - sendCodeTime) / 1000);
      if (surplusTime > 0) {
        this.startCountDown(surplusTime);
      }
    }
  },
  methods: {
    toCodeInput(e) {
    },
    /**
     * 开启倒计时
     */
    startCountDown(surplusTime) {
      if (this.isSending) {
        return;
      }
      this.isSending = true;
      this.surplusTime = surplusTime;
      let interval = setInterval(() => {
        this.surplusTime--;
        if (this.surplusTime <= 0) {
          clearInterval(interval);
          this.isSending = false;
          this.surplusTime = 60;
        }
      }, 1000);
    },

    /**
     * toTo
     */
    toTo() {
      this.$emit("toTo");
    },

    /**
     * 处理to的值
     */
    handleTo(param) {
      if (param.to === "") {
        return "";
      }
      // 如果是邮箱
      if (this.param.typeCode === "email") {
        // 将@前面的字符替换为*，只保留开始和结尾的字符
        let split = param.to.split("@");
        // 开始的字符
        let start = split[0].substring(0, 1);
        // 如果小于3个字符，直接返回
        if (split[0].length <= 3) {
          return param.to;
        }

        // 如果大于5位数
        if (split[0].length > 5) {
          return split[0].substring(0, 3) + "***@" + split[1];
        }

        // 结尾的字符
        let end = split[0].substring(split[0].length - 1, split[0].length);
        // 中间的*号数量
        let middle = split[0].length - start.length - end.length;
        // 中间的*号
        let middleStr = "";
        for (let i = 0; i < middle; i++) {
          middleStr += "*";
        }
        return start + middleStr + end + "@" + split[1];
      }
      // 如果是手机
      if (this.param.typeCode === "phone") {
        // 如果超过11位，保留前3位和后4位
        if (param.to.length > 11) {
          // 获取中间星号的数量
          let middle = param.to.length - 3 - 4;
          let middleStr = "";
          for (let i = 0; i < middle; i++) {
            middleStr += "*";
          }
          return "+" + param.phoneAreaCode + " " + param.to.substring(0, 3) + middleStr + param.to.substring(param.to.length - 4, param.to.length);
        }
        // 如果小于11位，保留前2和后2位
        if (param.to.length <= 11) {
          // 获取中间星号的数量
          let middle = param.to.length - 2 - 2;
          let middleStr = "";
          for (let i = 0; i < middle; i++) {
            middleStr += "*";
          }
          return "+" + param.phoneAreaCode + " " + param.to.substring(0, 2) + middleStr + param.to.substring(param.to.length - 2, param.to.length);
        }
        // 获取前面1位，中间的*号，后面的1位
        let paramStr = param.to.substring(0, 1);
        for (let i = 0; i < param.to.length - 2; i++) {
          paramStr += "*";
        }
        return paramStr + param.to.substring(param.to.length - 1, param.to.length);
      }
    },

    focus() {
      this.param = this.$kt.storage.get("loginParam");
      this.isFocus = true;
    },
    blur() {
      this.isFocus = false;
      this.$emit("blur");
    },
    /**
     * 发送验证码
     */
    sendCode() {
      this.$refs.sendCodeButton.loading("发送中", 99999999);
      this.$kt.requestSecurity.send({
        uri: "/user-account-web/userAccountLogin/sendLoginVerificationCode",
        isReconnect: false,
        data: {
          ...this.param,
        },
        stateSuccess: (res) => {
          console.log("发送验证码成功");
          this.$refs.sendCodeButton.success(res.msg, 2000);
          setTimeout(() => {
            // 存储发送验证码的时间
            this.$kt.storage.set("sendCodeTime", new Date().getTime());
            this.startCountDown(60);
          })
        },
        stateFail: (res) => {
          console.log("发送验证码失败");
          this.$refs.sendCodeButton.error(res.errMsg);
        }
      });
    }
  },
  watch: {
    param: {
      handler(val) {
        //
        let paramValue = this.param.value + ""

        if (paramValue.length === 6) {
          this.isCheck = true;
          this.$refs.checkButton.loading();
          this.$kt.requestSecurity.send({
            uri: "/user-account-web/userAccountLogin/loginByEmailAndVerificationCode",
            isReconnect: false,
            data: {
              email: this.param.to,
              verificationCode: this.param.value
            },
            stateSuccess: (res) => {
              console.log("login:====:::"+JSON.stringify(res));
              this.$kt.storage.set("token", res.data.token);
              this.$refs.checkButton.success(res.msg, 1500);
              this.$kt.userAccount.setSelf(res.data.userAccount);
              this.$kt.userAccount.setIsLogin(true);
              // 发送登录成功事件
              this.$kt.event.emit("login:success");
              // 返回上一页
              setTimeout(() => {
                uni.navigateBack();
              }, 1500);

            },
            stateFail: (res) => {
              setTimeout(() => {
                this.isCheck = false;
              }, 1500);
              this.$refs.checkButton.error(res.errMsg, 1500);

            }
          });
        }
      },
      deep: true,
      immediate: true
    }
  }
}
</script>

<style lang="scss" scoped>
.box {
  text-align: center;
}

.input-box {
  width: 600rpx;
  margin: 0 auto;
  position: relative;
}

.input {
  font-size: 40rpx;
  letter-spacing: 20rpx;
}

.line {
  width: 100%;
  height: 2px;
  border-radius: 5rpx;
  background-color: #000;
  margin-top: 10px;
}

.verify-code-input-box {
  display: flex;
  justify-content: space-between;
  margin-top: 20rpx;
}

.to {
  font-size: 40rpx;
  color: #000000;
  letter-spacing: 1rpx;
}

.to:active {
  opacity: .8;
  transform: scale(.98);
}

.code-input {
  width: 100%;
  height: 100%;
  font-size: 32rpx;
  text-align: center;
  border: none;
  outline: none;
  background-color: #f2f2f2;
  padding: 30rpx 10rpx 30rpx 10rpx;
  box-sizing: border-box;
  letter-spacing: 5rpx;
  border-radius: 20rpx;
  font-weight: bold;
}


</style>
